package com.mjh.zhujianju.service.agency.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.mjh.zhujianju.util.FileUrlAdapter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.livew.framework.base.model.FileEO;
import com.livew.framework.base.service.FileService;
import com.livew.framework.base.service.impl.BaseServiceImpl;
import com.livew.framework.enums.EStatus;
import com.livew.framework.exception.XTBusinessException;
import com.livew.framework.page.PagedBeanUtil;
import com.livew.framework.page.PagedResult;
import com.livew.framework.pojo.LoginUserInfo;
import com.livew.framework.sql.XTSqlUtils;
import com.livew.framework.utils.XTCurrentUser;
import com.livew.framework.utils.XTEntityUtils;
import com.livew.framework.utils.XTListUtils;
import com.mjh.zhujianju.dao.agency.PolicyMapper;
import com.mjh.zhujianju.enums.BusinessEnum;
import com.mjh.zhujianju.enums.PolicyEnum;
import com.mjh.zhujianju.model.agency.OrganizationEO;
import com.mjh.zhujianju.model.agency.PolicyEO;
import com.mjh.zhujianju.model.base.ContentEO;
import com.mjh.zhujianju.service.agency.OrganizationService;
import com.mjh.zhujianju.service.agency.PolicyService;
import com.mjh.zhujianju.service.base.ContentService;
import com.mjh.zhujianju.service.base.HitsService;
import com.mjh.zhujianju.vo.agency.PolicyVO;

/**
 * @author liuyang
 * @Description: 政策
 * @date 2018/8/9 22:32
 */
@Service
public class PolicyServiceImpl extends BaseServiceImpl<PolicyEO> implements PolicyService {

    @Autowired
    private PolicyMapper policyMapper;

    @Autowired
    private FileService fileService;

    @Autowired
    private ContentService contentService;

    @Autowired
    private HitsService hitsService;
    
    @Autowired
    private OrganizationService organizationService;

    public PolicyServiceImpl(PolicyMapper policyMapper) {
        super(policyMapper);
    }

    @Override
    public List<PolicyVO> queryPolicyIndexList() {
        return queryPolicyVOList(3L,null);
    }

    @Override
    public List<PolicyVO> queryPolicyList(String type) {
        return queryPolicyVOList(null,type);
    }

    @Override
    public PolicyVO queryPolicyInfo(Long id) {
        PolicyVO policyVO = policyMapper.queryPolicyInfo(id);
        if (policyVO == null){
            return null;
        }

        String type = BusinessEnum.TYPE_ANNOUNCEMENT.getCode();

        //查询内容
        ContentEO contentEO = contentService.queryContentByTypeAndId(type,id);
        if (contentEO != null){
            policyVO.setContent(contentEO.getContent());
        }

        //添加浏览量
        hitsService.updateNumber(type,id);

        //阅读数量
        Long hitsTotal = hitsService.queryHitsTotal(type,id);
        policyVO.setTotalHits(hitsTotal);

        return policyVO;
    }

    private List<PolicyVO> queryPolicyVOList(Long limit,String type){
        List<PolicyVO> list = policyMapper.queryPolicyList(type);
        if (CollectionUtils.isEmpty(list)){
            return null;
        }

        if (limit != null){
			list = list.stream().limit(limit).collect(Collectors.toList());
        }

		List<Long> caseIds = list.stream().map(policyVO -> policyVO.getId()).distinct().collect(Collectors.toList());

        List<FileEO> fileList = fileService.getFileByIds(caseIds,PolicyEO.class.getName(),null);
        if (CollectionUtils.isEmpty(fileList)){
            return list;
        }

        SimpleDateFormat sdf1 = new SimpleDateFormat("MM-dd");
        list.stream().forEach(policyVO -> {
            fileList.stream().forEach(fileEO -> {
            	 policyVO.setRemark2(sdf1.format(policyVO.getReleaseTime()));
                if (policyVO.getId().equals(fileEO.getCaseId())){
                    policyVO.setFileAction(FileUrlAdapter.assemblyAction(fileEO.getId()));
                }
            });
        });
        return list;
    }

	@Override
	public void saveInfo(PolicyVO vo) throws XTBusinessException {
		PolicyEO eo = new PolicyEO();
		BeanUtils.copyProperties(vo, eo);
		eo.setStatus(EStatus.active.getCode());
		eo.setReleaseTime(new Date());
		LoginUserInfo info = 	XTCurrentUser.getCurrentUser();
		if(info!=null) {
			eo.setDeptId(info.getDeptId());
		}
		this.save(eo);
		if (vo.getFileEO()!=null) {
			List<Long> fileIds = new ArrayList<>();
			fileIds.add(vo.getFileEO().getId());
			fileService.updateList(fileIds, eo.getId(), PolicyEO.class.getName());
		}
		if (vo.getContentEO().getContent() != null) {
			contentService.saveOrUpdate(BusinessEnum.TYPE_POLICY.getCode(), eo.getId(), vo.getContentEO().getContent());
		}
		
	}

	@Override
	public void updateInfo(PolicyVO vo) throws XTBusinessException {
		PolicyEO eo = new PolicyEO();
		BeanUtils.copyProperties(vo, eo);
		LoginUserInfo info = 	XTCurrentUser.getCurrentUser();
		if(info!=null) {
			eo.setDeptId(info.getDeptId());
		}
		eo.setStatus(EStatus.active.getCode());
		eo.setReleaseTime(new Date());
		this.updateByPrimaryKeySelective(eo);
		if (vo.getFileEO()!=null) {
			List<Long> fileIds = new ArrayList<>();
			fileIds.add(vo.getFileEO().getId());
			fileService.updateList(fileIds, eo.getId(), PolicyEO.class.getName());
		}
		// 更新内容
		contentService.saveOrUpdate(BusinessEnum.TYPE_POLICY.getCode(), eo.getId(), vo.getContentEO().getContent());
	}

	@Override
	public PagedResult<PolicyVO> getVOPage(PolicyVO vo) {
		Integer pageNo = vo.getPageNo() == null ? 1 : vo.getPageNo();
		Integer pageSize = vo.getPageSize() == null ? 15 : vo.getPageSize();
		PageHelper.startPage(pageNo, pageSize);
		if(vo.getTitle()!=null) {
			vo.setTitle(XTSqlUtils.replaceSeparator(vo.getTitle()));
		}
		List<PolicyEO> list = policyMapper.selectPagination(vo);
		PagedResult<PolicyEO> page = PagedBeanUtil.toPagedResult(list);
		PagedResult<PolicyVO> result = new PagedResult<>();
		BeanUtils.copyProperties(page, result);
		if (!XTListUtils.isEmpty(list)) {
			List<Long> ids = XTEntityUtils.getIdList(list);
			List<PolicyVO> voList = new ArrayList<PolicyVO>();
			Map<Long, FileEO> files = fileService.getMapTopOne(ids, PolicyEO.class.getName(), null);
			for (PolicyEO policy : list) {
				PolicyVO d = new PolicyVO();
				BeanUtils.copyProperties(policy, d);
				voList.add(d);
				d.setTypeName(PolicyEnum.getName(d.getType()));
				FileEO file = files.get(d.getId());
				if (file != null) {
					d.setFileEO(file);
				}
			}
			result.setDataList(voList);
		}
		return result;
	}

	@Override
	public PolicyVO getInfo(Long id) throws XTBusinessException{
		PolicyEO policy = super.getByPrimaryKey(id);
		if (policy != null) {
			PolicyVO vo = new PolicyVO();
			BeanUtils.copyProperties(policy, vo);
			ContentEO content =	this.contentService.queryContentByTypeAndId(BusinessEnum.TYPE_POLICY.getCode(), policy.getId());
			List<FileEO> files = fileService.getFileById(id, PolicyEO.class.getName(), null);
			if(!XTListUtils.isEmpty(files)) {
				vo.setFileEO(files.get(0));
			}
			vo.setTypeName(PolicyEnum.getName(vo.getType()));
			vo.setContentEO(content);
			return vo;
		}

		return null;
	}
    
    
    
    
}
